package ModelLayer;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Collection;

/**
 * 
 * @author Mads Nielsen
 * @version 12-4-2011
 */
public class AddressBook {
    
    private static AddressBook instance;
    
    private HashMap<Integer, Person> persons;

    private AddressBook() {
        
        persons = new HashMap<Integer, Person>();
        
    }
    
    public static AddressBook getInstance() {
        
        if(instance == null) {
            instance = new AddressBook();
        }
        
        return instance;
    }
    
    public void clear() {
        persons.clear();
    }
    
    public boolean containsPerson(Person person) {
        return persons.containsValue(person);
    }
    
    public Person getPerson(Integer id) {
        return persons.get(id);
    }
    
    public int addPerson(Person person) {
        Integer id = getUniqueId();
        
        person.setId(id);
        persons.put(id, person);
        
        return id;
    }
    
    private Integer getUniqueId() {
        
        int greatestId = 0;
        
        for(Person person : persons.values()) {
            if(person.getId() > greatestId) {
                greatestId = person.getId();
            }
        }
        
        return (greatestId + 1);
        
    }
    
    public boolean removePerson(Person person) {
        Person removed = persons.remove(person.getId());
        return removed != null;
    }
    
    public ArrayList<Person> getAllPersons() {
        
        ArrayList<Person> list = new ArrayList<Person>();
        
        for(Person person : persons.values()) {
            list.add(person);
        }
        
        return list;
    }
    
    public ArrayList<Person> search(String query) {
        
        ArrayList<Person> results = new ArrayList<Person>();
        
        for(Person person : persons.values()) {
            
            // compare person lowercase name with lowercase query
            if(person.getName().toLowerCase().contains(query.toLowerCase())) {
                results.add(person);
            }
            
        }
        
        return results;
        
    }
    
}
